package com.bw.broker.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.broker.mapper.TbCorporationMapper;
import com.bw.broker.service.TbCorporationService;
import com.bw.broker.service.TbHouseBrokerService;
import com.bw.broker.mapper.TbHouseBrokerMapper;
import com.bw.house.client.HouseFeignService;
import com.bw.po.TbCorporation;
import com.bw.po.TbHouseBroker;
import com.bw.po.TbHouseInfo;
import com.bw.result.ResponseState;
import com.bw.result.ResultVo;
import com.bw.util.DuanxinUtils;
import com.bw.util.SnowflakeIdWorker;
import com.bw.vo.*;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.bw.result.ResponseState.*;

/**
* @author 25728
* @description 针对表【tb_house_broker(经纪人)】的数据库操作Service实现
* @createDate 2023-11-11 10:30:24
*/
@Service
public class TbHouseBrokerServiceImpl extends ServiceImpl<TbHouseBrokerMapper, TbHouseBroker>
    implements TbHouseBrokerService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbHouseBrokerMapper tbHouseBrokerMapper;
    @Autowired
    private HouseFeignService houseFeignService;
    @Autowired
    private TbCorporationService tbCorporationService;

    @Override
    public ResultVo add(TbHouseBrokerVo tbHouseBrokerVo) {
        TbHouseBroker tbHouseBroker = new TbHouseBroker();
        //将vo对象转为po对象
        BeanUtils.copyProperties(tbHouseBrokerVo, tbHouseBroker);
        QueryWrapper<TbHouseBroker> tbHouseInfoQueryWrapper = new QueryWrapper<>();
        tbHouseInfoQueryWrapper.lambda().eq(TbHouseBroker::getName, tbHouseBrokerVo.getName());
        //获取一个经纪人
        TbHouseBroker one = tbHouseBrokerMapper.selectOne(tbHouseInfoQueryWrapper);
        if (null != one) {
            return ResultVo.FAILED(BROKER_EXIST);
        }
        //添加
        int save = tbHouseBrokerMapper.insert(tbHouseBroker);
        return save == 1 ? ResultVo.SUCCESS() : ResultVo.FAILED(INSERT_ERROR);
    }

    @Override
    public ResultVo update(TbHouseBrokerVo tbHouseBrokerVo) {
        TbHouseBroker tbHouseBroker = new TbHouseBroker();
        //将vo对象转为po对象
        BeanUtils.copyProperties(tbHouseBrokerVo, tbHouseBroker);
        QueryWrapper<TbHouseBroker> tbHouseInfoQueryWrapper = new QueryWrapper<>();
        tbHouseInfoQueryWrapper.lambda().eq(TbHouseBroker::getName, tbHouseBrokerVo.getName());
        //获取一个经纪人
        TbHouseBroker one = tbHouseBrokerMapper.selectOne(tbHouseInfoQueryWrapper);
        if (null == one) {
            return ResultVo.FAILED(BROKER_NOT_EXIST);
        }
        //修改
        int update = tbHouseBrokerMapper.updateById(tbHouseBroker);
        return update == 1 ? ResultVo.SUCCESS() : ResultVo.FAILED(UPDATE_ERROR);
    }

    @Override
    public ResultVo deleted(TbHouseBrokerVo tbHouseBrokerVo) {
        TbHouseBroker tbHouseBroker = new TbHouseBroker();
        //将vo对象转为po对象
        BeanUtils.copyProperties(tbHouseBrokerVo, tbHouseBroker);
        QueryWrapper<TbHouseBroker> tbHouseInfoQueryWrapper = new QueryWrapper<>();
        tbHouseInfoQueryWrapper.lambda().eq(TbHouseBroker::getName, tbHouseBrokerVo.getName());
        //获取一个经纪人
        TbHouseBroker one = tbHouseBrokerMapper.selectOne(tbHouseInfoQueryWrapper);
        if (null == one) {
            return ResultVo.FAILED(BROKER_NOT_EXIST);
        }
        //手中还有房源无法删除
        if (one.getRentingHouseCount()!=0||one.getSecondHandHouseCount()!=0||one.getBridalChamberCount()!=0){
            return ResultVo.FAILED(BROKER_HAS_HOUSE);
        }
        //删除经纪人
        int deleted = tbHouseBrokerMapper.deleteById(tbHouseBroker);
        return deleted == 1 ? ResultVo.SUCCESS() : ResultVo.FAILED(DELETE_ERROR);
    }

    @Override
    public ResultVo list(TbHouseBrokerVo tbHouseBrokerVo) {
        //分页
        Page<TbHouseBroker> tbHouseInfoPage = null;
        if (tbHouseBrokerVo.getPageNum() != null && tbHouseBrokerVo.getPageSize() != null) {
            tbHouseInfoPage = new Page<>(tbHouseBrokerVo.getPageNum(), tbHouseBrokerVo.getPageSize());
        }
        Page<TbHouseBrokerVo> page = tbHouseBrokerMapper.Brokerpage(tbHouseInfoPage,tbHouseBrokerVo);
        return ResultVo.SUCCESS(page);
    }

    @Override
    public TbHouseBrokerVo ById(IdVo idVo) {
        TbHouseBrokerVo tbHouseBrokerVo = tbHouseBrokerMapper.getById(idVo.getId());
        return tbHouseBrokerVo;
    }

    @Override
    public ResultVo getByName(String name) {
        //将vo对象转为po对象
        QueryWrapper<TbHouseBroker> tbHouseInfoQueryWrapper = new QueryWrapper<>();
        tbHouseInfoQueryWrapper.lambda().eq(TbHouseBroker::getName, name);
        //获取一个经纪人
        TbHouseBroker tbHouseBroker = tbHouseBrokerMapper.selectOne(tbHouseInfoQueryWrapper);
        if (null == tbHouseBroker) {
            return ResultVo.FAILED(BROKER_NOT_EXIST);
        }
        return ResultVo.SUCCESS(tbHouseBroker.getId());
    }

    @Override
    public ResultVo sendCode(LoginVo loginVo) {
        DuanxinUtils duanxinUtils = new DuanxinUtils();
        if (StringUtils.isEmpty(loginVo.getPhone())) {
            return ResultVo.FAILED(MOBILE_NOT_NULL);
        }
        Object o = redisTemplate.opsForValue().get("code" + loginVo.getPhone());
        if (null != o) {
            //五分钟内 返回成功 返回同一条验证码
            return ResultVo.SUCCESS();
        }
        //
        Object object = redisTemplate.opsForValue().get("send" + loginVo.getPhone());
        if (null != object) {
            //一分钟内 返回失败 不允许再次发送验证码
            return ResultVo.FAILED(CODE_NOT_REPEATED_REQUEST);
        }
        //判断是否是员工
        QueryWrapper<TbHouseBroker> tbHouseInfoQueryWrapper = new QueryWrapper<>();
        tbHouseInfoQueryWrapper.lambda().eq(TbHouseBroker::getPhone, loginVo.getPhone());
        TbHouseBroker tbHouseBroker = tbHouseBrokerMapper.selectOne(tbHouseInfoQueryWrapper);
        Boolean adminByPhone = houseFeignService.getAdminByPhone(loginVo.getPhone());
        if (!adminByPhone && tbHouseBroker == null) {
            return ResultVo.FAILED(EMPLOYEE_NOT_EXIST);
        }
            String code = RandomUtil.randomNumbers(4);
            Boolean sendFlag = duanxinUtils.sendDuanxin(loginVo.getPhone(), code);
            System.out.println(loginVo.getPhone() + "的短信验证码是" + code);
            if (sendFlag) {
                //发送成功后将验证码存入redis中
                redisTemplate.opsForValue().set("code" + loginVo.getPhone(), code, 5, TimeUnit.MINUTES);
                //发送成功的标识  标识一分钟不允许发送
                redisTemplate.opsForValue().set("send" + loginVo.getPhone(), "", 1, TimeUnit.MINUTES);
            }
        return sendFlag ? ResultVo.SUCCESS() : ResultVo.FAILED(SEND_CODE_ERROR);
    }


    @Override
    public ResultVo login(LoginVo loginVo) {
        //手机号验证码登录
        if (StringUtils.isEmpty(loginVo.getPhone())){
            return ResultVo.FAILED(MOBILE_NOT_NULL);
        }
        QueryWrapper<TbHouseBroker> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbHouseBroker::getPhone,loginVo.getPhone());
        TbHouseBroker broker = tbHouseBrokerMapper.selectOne(queryWrapper);
        if (broker==null){
            return ResultVo.FAILED(EMPLOYEE_NOT_EXIST);
        }
        if (broker.getStatus()==1){
            //经纪人已经离职或被禁止
            return ResultVo.FAILED(EMPLOYEE_NOT_EXIST);
        }
        String jwsKey="SearchHouse";
        //判断验证码
        String redisCode = (String) redisTemplate.opsForValue().get("code" + loginVo.getPhone());
        if (null==redisCode){
            //验证码失效
            return ResultVo.FAILED(CODE_ERROR_EXPIRED);
        }
        if (!redisCode.equals(loginVo.getCode())){
            //登录失败
            return ResultVo.FAILED(CODE_ERROR);
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, jwsKey)
                .claim("id",broker.getId()).compact();
        redisTemplate.opsForValue().set(token,token,5,TimeUnit.MINUTES);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token",token);
        hashMap.put("broker", JSON.toJSONString(broker));
        return ResultVo.SUCCESS(hashMap);
    }

    @Override
    public int subtractBrokerHouse(BrokerHouseNumVo brokerHouseNumVo) {
        TbHouseBroker tbHouseBroker = tbHouseBrokerMapper.selectById(brokerHouseNumVo.getBrokerId());
        if (tbHouseBroker==null){
            return 0;
        }
        if (brokerHouseNumVo.getTypeId()==1){
            //新房
            tbHouseBroker.setBridalChamberCount(tbHouseBroker.getBridalChamberCount()-1);
            return tbHouseBrokerMapper.updateById(tbHouseBroker);
        }
        if (brokerHouseNumVo.getTypeId()==2){
            //二手房
            tbHouseBroker.setSecondHandHouseCount(tbHouseBroker.getSecondHandHouseCount()-1);
            return tbHouseBrokerMapper.updateById(tbHouseBroker);
        }
        if (brokerHouseNumVo.getTypeId()==3){
            //租房
            tbHouseBroker.setRentingHouseCount(tbHouseBroker.getRentingHouseCount()-1);
            return tbHouseBrokerMapper.updateById(tbHouseBroker);
        }
        return 0;
    }

    @Override
    public int appendBrokerHouse(BrokerHouseNumVo brokerHouseNumVo) {
        TbHouseBroker tbHouseBroker = tbHouseBrokerMapper.selectById(brokerHouseNumVo.getBrokerId());
        if (tbHouseBroker==null){
            return 0;
        }
        if (brokerHouseNumVo.getTypeId()==1){
            //新房
            tbHouseBroker.setBridalChamberCount(tbHouseBroker.getBridalChamberCount()+1);
            return tbHouseBrokerMapper.updateById(tbHouseBroker);
        }
        if (brokerHouseNumVo.getTypeId()==2){
            //二手房
            tbHouseBroker.setSecondHandHouseCount(tbHouseBroker.getSecondHandHouseCount()+1);
            return tbHouseBrokerMapper.updateById(tbHouseBroker);
        }
        if (brokerHouseNumVo.getTypeId()==3){
            //租房
            tbHouseBroker.setRentingHouseCount(tbHouseBroker.getRentingHouseCount()+1);
            return tbHouseBrokerMapper.updateById(tbHouseBroker);
        }
        return 0;
    }

    @Override
    public ResultVo corporationList() {
        List<TbCorporation> tbHouseCorporationList = tbCorporationService.list();
        return ResultVo.SUCCESS(tbHouseCorporationList);
    }

    @Override
    public Set getByCountyId(Integer countyId) {
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        //查询这个区县的经纪人
        QueryWrapper<TbHouseBroker> tbHouseBrokerQueryWrapper = new QueryWrapper<>();
        tbHouseBrokerQueryWrapper.lambda().eq(TbHouseBroker::getCountyId,countyId);
        List<TbHouseBroker> list = list(tbHouseBrokerQueryWrapper);
        for (TbHouseBroker tbHouseBroker : list) {
            zSetOperations.add("brokerHouse"+countyId,tbHouseBroker.getName(),tbHouseBroker.getSuccessSellCount());
        }
        Set brokerSet = zSetOperations.range("brokerHouse" + countyId, 0, -1);
        return brokerSet;
    }
}




